//
//  XHTrafficPackageViewController.m
//  umibus
//
//  Created by 冷山 on 16/6/16.
//  Copyright © 2016年 lexingsoft. All rights reserved.
//

#import "XHTrafficPackageViewController.h"
#import "XHUseTrafficViewController.h"
#import "XHTrafficPackageDetailViewController.h"

#import "XHTrafficPageCell.h"

#import "Services.h"

#import <SVPullToRefresh/SVPullToRefresh.h>

static const NSUInteger kPageSize = 20;
static const NSUInteger kPageInit = 0;

@interface XHTrafficPackageViewController ()<UITableViewDelegate,UITableViewDataSource,XHTrafficPageCellDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *ui_scrollView;
@property (weak, nonatomic) IBOutlet UIButton *ui_menuItem1;
@property (weak, nonatomic) IBOutlet UIButton *ui_menuItem2;
@property (weak, nonatomic) IBOutlet UIView *ui_menuItemTagView;

@property (strong, nonatomic) UITableView *ui_tableView1;
@property (strong, nonatomic) UITableView *ui_tableView2;

@property (strong, nonatomic) NSMutableArray *m_messagesArray;
@property (strong, nonatomic) NSMutableArray *m_messagesArray2;
@property (assign, nonatomic) NSUInteger page;
@property (assign, nonatomic) BOOL hasNextPage;
@property (assign, nonatomic) NSUInteger page2;
@property (assign, nonatomic) BOOL hasNextPage2;

@end

@implementation XHTrafficPackageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.ui_scrollView.bounces = NO;
    [self.ui_menuItem1 setTitleColor:[ColorManager colorWithHexString:@"#5997A4"] forState:UIControlStateSelected];
    [self.ui_menuItem2 setTitleColor:[ColorManager colorWithHexString:@"#5997A4"] forState:UIControlStateSelected];
    self.ui_tableView1=[[UITableView alloc] initWithFrame:CGRectMake(self.ui_scrollView.frame.size.width*0, 0, self.ui_scrollView.frame.size.width, self.ui_scrollView.frame.size.height) style:UITableViewStyleGrouped];
    self.ui_tableView1.delegate=self;
    self.ui_tableView1.dataSource=self;
    self.ui_tableView1.backgroundColor = [ColorManager colorWithHexString:@"F4F4F4"];
    [self.ui_tableView1 setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.ui_scrollView addSubview:self.ui_tableView1];
    
    self.ui_tableView2=[[UITableView alloc] initWithFrame:CGRectMake(self.ui_scrollView.frame.size.width*0, 0, self.ui_scrollView.frame.size.width, self.ui_scrollView.frame.size.height) style:UITableViewStyleGrouped];
    self.ui_tableView2.delegate=self;
    self.ui_tableView2.dataSource=self;
    self.ui_tableView2.backgroundColor = [ColorManager colorWithHexString:@"F4F4F4"];
    [self.ui_tableView2 setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.ui_scrollView addSubview:self.ui_tableView2];
    
    [self.ui_tableView1 registerNib:[UINib nibWithNibName:@"XHTrafficPageCell" bundle:nil] forCellReuseIdentifier:XHTrafficPageCellIdentifier];
    [self.ui_tableView2 registerNib:[UINib nibWithNibName:@"XHTrafficPageCell" bundle:nil] forCellReuseIdentifier:XHTrafficPageCellIdentifier];
    [self menuItemAction:self.ui_menuItem1];
    
    self.page=kPageInit;
    [self.ui_tableView1 addInfiniteScrollingWithActionHandler:^{
        if (!self.hasNextPage)
        {
            //[PromptAction showErrorPrompt:@"暂无更多数据"];
        }
        if (self.m_messagesArray.count>=kPageSize){
            [self getTraffic:self.page+1];
            return;
        }
        [self.ui_tableView1.infiniteScrollingView stopAnimating];
    }];
    [self.ui_tableView1 addPullToRefreshWithActionHandler:^{
        self.page=kPageInit;
        [self getTraffic:self.page];
    }];
    [PublicMethod setPullToRefreshView:self.ui_tableView1];
    
    [self.ui_tableView2 addInfiniteScrollingWithActionHandler:^{
        
        if (!self.hasNextPage2)
        {
            //[PromptAction showErrorPrompt:@"暂无更多数据"];
        }
        if (self.m_messagesArray2.count>=kPageSize)
        {
            [self getArchivedTraffic:self.page2+1];
            return;
        }
        [self.ui_tableView2.infiniteScrollingView stopAnimating];
    }];
    [self.ui_tableView2 addPullToRefreshWithActionHandler:^{
        
        self.page2=kPageInit;
        [self getArchivedTraffic:self.page2];
    }];
    [PublicMethod setPullToRefreshView:self.ui_tableView2];

}

- (IBAction)menuItemAction:(UIButton *)sender
{
    [self.ui_menuItem1 setSelected:NO];
    [self.ui_menuItem2 setSelected:NO];
    [sender setSelected:YES];
    [UIView animateWithDuration:0.3f animations:^{
        CGRect frame=self.ui_menuItemTagView.frame;
        frame.origin.x=sender.frame.origin.x;
        frame.size.width=sender.frame.size.width;
        self.ui_menuItemTagView.frame=frame;
    }];
    NSInteger tag=sender.tag;
    [self.ui_scrollView setContentOffset:CGPointMake(self.ui_scrollView.frame.size.width*tag, 0) animated:YES];
}


- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    if ([self.ui_menuItem1 isSelected])
    {
        CGRect frame=self.ui_menuItemTagView.frame;
        frame.origin.x=self.ui_menuItem1.frame.origin.x;
        frame.size.width=self.ui_menuItem1.frame.size.width;
        self.ui_menuItemTagView.frame=frame;
    }
    else
    {
        CGRect frame=self.ui_menuItemTagView.frame;
        frame.origin.x=self.ui_menuItem2.frame.origin.x;
        frame.size.width=self.ui_menuItem2.frame.size.width;
        self.ui_menuItemTagView.frame=frame;
    }
    //设置ScrollView的Size,Offset
    self.ui_scrollView.contentSize=CGSizeMake(self.ui_scrollView.frame.size.width*2, self.ui_scrollView.frame.size.height);
    self.ui_tableView1.frame=CGRectMake(self.ui_scrollView.frame.size.width*0, 0, self.ui_scrollView.frame.size.width, self.ui_scrollView.frame.size.height);
    self.ui_tableView2.frame=CGRectMake(self.ui_scrollView.frame.size.width*1, 0, self.ui_scrollView.frame.size.width, self.ui_scrollView.frame.size.height);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.page = kPageInit;
    self.page2 = kPageInit;
    [self getTraffic:self.page];
    [self getArchivedTraffic:self.page2];
}

//可使用
- (void)getTraffic:(NSInteger)page
{
    page = self.page;
    if (!self.m_messagesArray)
    {
        [self showLoadingView];
    }
    if([[DataManager sharedInstance] isLogin])
    {
        [ServiceManager getUserTrafficPackageWithType:@"N" pageIndex:page success:^(NSDictionary *data) {
            if (page == kPageInit || self.m_messagesArray == nil)
            {
                self.m_messagesArray = [NSMutableArray array];
            }
            NSArray * datas = data[@"result"];
            if ([datas isKindOfClass:[NSArray class]])
            {
                if (datas.count>0)
                {
                    self.page=page;
                    [self.m_messagesArray addObjectsFromArray:datas];
                }
//                if (self.m_messagesArray.count ==0)
//                {
//                    self.ui_tableView1.hidden = YES;
//                }
//                else
//                {
//                    self.ui_tableView1.hidden = NO;
//                }
            }
            else
            {
                
            }
            [self.ui_tableView1 reloadData];
            [self.ui_tableView1.infiniteScrollingView stopAnimating];
            [PublicMethod setFinishRefreshView:self.ui_tableView1];
            [self performSelector:@selector(stopAnimate:) withObject:nil afterDelay:2.0];
            [self hideLoadingView];
            
        } failure:^(NSDictionary *data) {
            [self.ui_tableView1.infiniteScrollingView stopAnimating];
            [self.ui_tableView1.pullToRefreshView stopAnimating];
            [self hideLoadingView];
        }];
    }
    else
    {
        self.ui_tableView1.hidden = YES;
        [self hideLoadingView];
    }

}

- (void)stopAnimate:(NSTimer*)timer
{
    [self.ui_tableView1.pullToRefreshView stopAnimating];
    [PublicMethod setPullToRefreshView:self.ui_tableView1];
}
//已使用
- (void)getArchivedTraffic:(NSInteger)page
{
    page = self.page2;
    if (!self.m_messagesArray2)
    {
        [self showLoadingView];
    }
    if([[DataManager sharedInstance] isLogin])
    {
        [ServiceManager getUserTrafficPackageWithType:@"Y" pageIndex:page success:^(NSDictionary *data) {
            if (page == kPageInit || self.m_messagesArray2 == nil)
            {
                self.m_messagesArray2 = [NSMutableArray array];
            }
            NSArray * datas = data[@"result"];
            if ([datas isKindOfClass:[NSArray class]])
            {
                if (datas.count>0)
                {
                    self.page2=page;
                    [self.m_messagesArray2 addObjectsFromArray:datas];
                }
//                if (self.m_messagesArray2.count ==0)
//                {
//                    self.ui_tableView2.hidden = YES;
//                }
//                else
//                {
//                    self.ui_tableView2.hidden = NO;
//                }
            }
            else
            {
                
            }
            [self.ui_tableView2 reloadData];
            [self.ui_tableView2.infiniteScrollingView stopAnimating];
            [PublicMethod setFinishRefreshView:self.ui_tableView2];
            [self performSelector:@selector(stopAnimate2:) withObject:nil afterDelay:2.0];
            [self hideLoadingView];
            
        } failure:^(NSDictionary *data) {
            [self.ui_tableView2.infiniteScrollingView stopAnimating];
            [self.ui_tableView2.pullToRefreshView stopAnimating];
            [self hideLoadingView];
        }];
    }
    else
    {
        self.ui_tableView1.hidden = YES;
        [self hideLoadingView];
    }
}
- (void)stopAnimate2:(NSTimer*)timer
{
    [self.ui_tableView2.pullToRefreshView stopAnimating];
    [PublicMethod setPullToRefreshView:self.ui_tableView2];
}
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger number = 0;
    if (tableView == self.ui_tableView1)
    {
        number = self.m_messagesArray.count;
        
    }
    else if (tableView == self.ui_tableView2)
    {
        number = self.m_messagesArray2.count;
    }
    return number;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger rows = 1;
    
    return rows;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = nil;
    if (tableView==self.ui_tableView1)
    {
        XHTrafficPageCell * cell = [tableView dequeueReusableCellWithIdentifier:XHTrafficPageCellIdentifier];
        cell.delegate = self;
        cell.ui_leftMoney.hidden = NO;
        cell.ui_useButton.hidden = NO;
        cell.ui_rightMoney.hidden = YES;
        cell.ui_useButton.tag = indexPath.section;
        NSDictionary * dic = self.m_messagesArray[indexPath.section];
        NSString * unit = @"";
        NSInteger usedTime = [dic[@"usedTime"] integerValue];
        NSInteger remainTime = [dic[@"remainTime"] integerValue];
        NSInteger total = usedTime + remainTime;
        NSInteger values = [dic[@"productValue"] integerValue];
        if (values>1000)
        {
            unit = @"G";
            values = values/1000;
        }
        else if (values<1000)
        {
            unit = @"M";
        }
        if ([dic[@"operatorName"] isEqualToString:@"中国移动"])
        {
            cell.ui_operator.backgroundColor = [ColorManager colorWithHexString:@"#59A46C"];
        }
        else if ([dic[@"operatorName"] isEqualToString:@"中国电信"])
        {
            cell.ui_operator.backgroundColor = [ColorManager colorWithHexString:@"#00AED2"];
        }
        else if ([dic[@"operatorName"] isEqualToString:@"中国联通"])
        {
            cell.ui_operator.backgroundColor = [ColorManager colorWithHexString:@"#E45252"];
        }
        cell.ui_content.text = [NSString stringWithFormat:@"%@ %ld%@(%ld/%ld)",dic[@"phoneLocation"],values,unit,total-remainTime,total];
        cell.ui_operator.text = [NSString stringWithFormat:@"%@",dic[@"operatorName"]];
        cell.ui_leftMoney.text = [NSString stringWithFormat:@"￥%@",dic[@"amount"]];
        cell.ui_timeLabel.text = [[NSDate dateWithString:dic[@"recDate"]] stringWithFormatter];
        
        return cell;
    }
    else if (tableView==self.ui_tableView2)
    {
        XHTrafficPageCell * cell = [tableView dequeueReusableCellWithIdentifier:XHTrafficPageCellIdentifier];
        cell.ui_leftMoney.hidden = YES;
        cell.ui_useButton.hidden = YES;
        cell.ui_rightMoney.hidden = NO;
        NSDictionary * dic = self.m_messagesArray2[indexPath.section];
        NSString * unit = @"";
        NSInteger usedTime = [dic[@"usedTime"] integerValue];
        NSInteger remainTime = [dic[@"remainTime"] integerValue];
        NSInteger total = usedTime + remainTime;
        NSInteger values = [dic[@"productValue"] integerValue];
        if (values>1000)
        {
            unit = @"G";
            values = values/1000;
        }
        else if (values<1000)
        {
            unit = @"M";
        }
        if ([dic[@"operatorName"] isEqualToString:@"中国移动"])
        {
            cell.ui_operator.backgroundColor = [ColorManager colorWithHexString:@"#59A46C"];
        }
        else if ([dic[@"operatorName"] isEqualToString:@"中国电信"])
        {
            cell.ui_operator.backgroundColor = [ColorManager colorWithHexString:@"#00AED2"];
        }
        else if ([dic[@"operatorName"] isEqualToString:@"中国联通"])
        {
            cell.ui_operator.backgroundColor = [ColorManager colorWithHexString:@"#E45252"];
        }
        cell.ui_content.text = [NSString stringWithFormat:@"%@ %ld%@(%ld/%ld)",dic[@"phoneLocation"],values,unit,usedTime,total];
        cell.ui_operator.text = [NSString stringWithFormat:@"%@",dic[@"operatorName"]];
        cell.ui_rightMoney.text = [NSString stringWithFormat:@"￥%@",dic[@"amount"]];
        cell.ui_timeLabel.text = [[NSDate dateWithString:dic[@"recDate"]] stringWithFormatter];
        
        return cell;
    }
    
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    XHTrafficPackageDetailViewController * viewController = [[XHTrafficPackageDetailViewController alloc]init];
    if (tableView == self.ui_tableView1)
    {
        NSDictionary * dic = self.m_messagesArray[indexPath.section];
        viewController.orderSn = dic[@"orderSn"];
    }
    else if (tableView == self.ui_tableView2)
    {
        NSDictionary * dic = self.m_messagesArray2[indexPath.section];
        viewController.orderSn = dic[@"orderSn"];
    }
    viewController.title = @"流量屯包详情";
    [self.navigationController pushViewController:viewController animated:YES];
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    CGFloat height = 0;
    if (section == 0)
    {
        height = 10;
    }
    else
    {
        height = 0.1;
    }
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    CGFloat height = 10;
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height=150;
    return height;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.ui_scrollView)
    {
        int x = scrollView.contentOffset.x/scrollView.frame.size.width;
        if (x==0)
        {
            [self menuItemAction:self.ui_menuItem1];
        }
        if (x==1)
        {
            [self menuItemAction:self.ui_menuItem2];
        }
    }
}

#pragma - mark XHTrafficPageCellDelegate

- (void)goUseAction:(UIButton*)button
{
    XHUseTrafficViewController * viewController = [[XHUseTrafficViewController alloc]init];
    viewController.title = @"使用流量屯包";
    viewController.packageDic = self.m_messagesArray[button.tag];
    [self.navigationController pushViewController:viewController animated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
